package redis

import (
	"cart_srv/cartsrv"
	"context"
	"fmt"
	"strconv"
)

// AddCart 添加购物车
func AddCart(userId, goodsId, num int, title, cover string, price float64) error {
	key := fmt.Sprintf("cart:user_id_%d:goods_id_%d", userId, goodsId)
	return Rdb.HMSet(context.Background(), key, map[string]interface{}{
		"GoodsId": goodsId,
		"Title":   title,
		"Cover":   cover,
		"Price":   price,
		"Num":     num,
		"Checked": 1,
	}).Err()
}

// ListCart 购物车列表
func ListCart(userId int) (listCart []*cartsrv.ListCart, err error) {
	key := fmt.Sprintf("cart:user_id_%d:goods_id_*", userId)
	keys, _ := Rdb.Keys(context.Background(), key).Result()
	fmt.Println("我是相关购物车的键名", keys)
	for _, k := range keys {
		val := Rdb.HGetAll(context.Background(), k).Val()

		goodsId, _ := strconv.Atoi(val["GoodsId"])
		title := val["Title"]
		cover := val["Cover"]
		price, _ := strconv.ParseFloat(val["Price"], 64)
		num, _ := strconv.Atoi(val["Num"])
		checked, _ := strconv.Atoi(val["Checked"])

		listCart = append(listCart, &cartsrv.ListCart{
			GoodsId: int64(goodsId),
			Title:   title,
			Cover:   cover,
			Price:   float32(price),
			Num:     int64(num),
			Checked: int64(checked),
		})
	}
	return
}
